"use client"

import { useState, useEffect } from "react"
import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import { Textarea } from "@/components/ui/textarea"
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@/components/ui/table"
import Link from "next/link"

interface Library {
  id: string
  name: string
  description: string | null
  eventCount: number
  createdAt: string
}

export default function LibrariesPage() {
  const [libraries, setLibraries] = useState<Library[]>([])
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState("")
  const [newLibrary, setNewLibrary] = useState({
    name: "",
    description: ""
  })

  useEffect(() => {
    fetchLibraries()
  }, [])

  async function fetchLibraries() {
    try {
      const response = await fetch("/api/admin/libraries")
      if (!response.ok) throw new Error("加载失败")
      const data = await response.json()
      setLibraries(data)
    } catch (err) {
      setError("无法加载事件库")
    } finally {
      setLoading(false)
    }
  }

  async function handleSubmit(e: React.FormEvent) {
    e.preventDefault()
    try {
      const response = await fetch("/api/admin/libraries", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(newLibrary)
      })

      if (!response.ok) throw new Error("创建失败")
      
      await fetchLibraries()
      setNewLibrary({ name: "", description: "" })
    } catch (err) {
      setError("创建事件库失败")
    }
  }

  async function handleDelete(id: string) {
    if (!confirm("确定要删除这个事件库吗？")) return

    try {
      const response = await fetch(`/api/admin/libraries/${id}`, {
        method: "DELETE"
      })

      if (!response.ok) throw new Error("删除失败")
      
      await fetchLibraries()
    } catch (err) {
      setError("删除事件库失败")
    }
  }

  if (loading) return <div className="text-center p-8">加载中...</div>

  return (
    <div className="max-w-4xl mx-auto p-8">
      <h1 className="text-2xl font-bold mb-6">事件库管理</h1>

      {/* 创建新事件库表单 */}
      <form onSubmit={handleSubmit} className="mb-8 p-4 border rounded-lg">
        <h2 className="text-lg font-semibold mb-4">创建新事件库</h2>
        <div className="space-y-4">
          <div>
            <label className="block text-sm font-medium mb-1">名称</label>
            <Input
              value={newLibrary.name}
              onChange={e => setNewLibrary(prev => ({ ...prev, name: e.target.value }))}
              required
            />
          </div>
          <div>
            <label className="block text-sm font-medium mb-1">描述</label>
            <Textarea
              value={newLibrary.description}
              onChange={e => setNewLibrary(prev => ({ ...prev, description: e.target.value }))}
            />
          </div>
          <Button type="submit">创建事件库</Button>
        </div>
      </form>

      {error && (
        <div className="text-red-500 mb-4">{error}</div>
      )}

      {/* 事件库列表 */}
      <div className="border rounded-lg overflow-hidden">
        <Table>
          <TableHeader>
            <TableRow>
              <TableHead>名称</TableHead>
              <TableHead>描述</TableHead>
              <TableHead>事件数量</TableHead>
              <TableHead>创建时间</TableHead>
              <TableHead>操作</TableHead>
            </TableRow>
          </TableHeader>
          <TableBody>
            {libraries.map(library => (
              <TableRow key={library.id}>
                <TableCell>{library.name}</TableCell>
                <TableCell>{library.description}</TableCell>
                <TableCell>{library.eventCount}</TableCell>
                <TableCell>
                  {new Date(library.createdAt).toLocaleDateString()}
                </TableCell>
                <TableCell>
                  <div className="space-x-2">
                    <Button
                      variant="outline"
                      size="sm"
                      asChild
                    >
                      <Link href={`/admin/libraries/${library.id}`}>
                        编辑
                      </Link>
                    </Button>
                    <Button
                      variant="destructive"
                      size="sm"
                      onClick={() => handleDelete(library.id)}
                    >
                      删除
                    </Button>
                  </div>
                </TableCell>
              </TableRow>
            ))}
          </TableBody>
        </Table>
      </div>
    </div>
  )
} 